package br.com.dlm.simuladoitil.fragments;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import br.com.dlm.simuladoitil.R;
import br.com.dlm.simuladoitil.basicas.Categoria;
import br.com.dlm.simuladoitil.util.ListaCategoriasAdapter;

public class CategoriasFragment extends GeralFragment {

    private List<Categoria> categorias;

    private ListView listViewCategorias;
    private TextView textViewMensagensCategorias;
    private ProgressBar progressBarCategorias;

    private CategoriaFragmentTask task;
    private boolean ocorreuErro;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        carregarConteudoTela();

        if (task == null) {
            if (possuiConexao()) {
                task = new CategoriaFragmentTask();
                task.execute();

                progressBarCategorias.setVisibility(View.VISIBLE);
                textViewMensagensCategorias.setVisibility(View.GONE);
            }
        } else {
            if (task.getStatus() == AsyncTask.Status.FINISHED) {
                carregarConteudoTela();
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_categorias, container, false);

        listViewCategorias = (ListView) view.findViewById(R.id.listViewCategorias);
        textViewMensagensCategorias = (TextView) view.findViewById(R.id.textViewMensagensCategorias);
        progressBarCategorias = (ProgressBar) view.findViewById(R.id.progressBarCategorias);

        listViewCategorias.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Categoria categoria = categorias.get(position);

                if (getActivity() instanceof OnClickOpcaoCategoriaListener) {
                    OnClickOpcaoCategoriaListener listener = (OnClickOpcaoCategoriaListener) getActivity();
                    listener.clickOpcaoCategoria(categoria);
                }
            }
        });

        return view;
    }

    public interface OnClickOpcaoCategoriaListener {
        void clickOpcaoCategoria(Categoria categoria);
    }

    private class CategoriaFragmentTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            try {
                conteudo().atualizarConteudoLocal();
            } catch (Exception excecao) {
               ocorreuErro = true;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            carregarConteudoTela();
        }
    }

    public void carregarConteudoTela() {
        categorias = conteudo().listarCategorias();

        ListaCategoriasAdapter categoriasAdapter = new ListaCategoriasAdapter(categorias);
        listViewCategorias.setAdapter(categoriasAdapter);

        if (categorias.isEmpty()) {
            textViewMensagensCategorias.setVisibility(View.VISIBLE);
            textViewMensagensCategorias.setText(getString(R.string.mensagem_caso_lista_categorias_vazia));
        } else {
            textViewMensagensCategorias.setVisibility(View.GONE);
        }

        progressBarCategorias.setVisibility(View.GONE);

        if (ocorreuErro) {
            Toast.makeText(getActivity(), getString(R.string.falha_atualizar_conteudo_local), Toast.LENGTH_LONG).show();
            ocorreuErro = false;
        }
    }

    private boolean possuiConexao() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }
}